package com.seari.utils;

import java.util.*;
import java.util.Map.Entry;

public class SortMap {

	public static void main(String[] args) {
		Map<String, Object> map = new HashMap<>();
		map.put("1", "0.0");
		map.put("2", "0.1");
		map.put("3", "0.1");
		map.put("4", "0.2333");
		map.put("5", "0.14343");
		map = orderMapValue(map, "asc", 4);
		for (Entry<String, Object> entry : map.entrySet()) {
			System.out.println(entry.getKey() + "====" + entry.getValue());
		}
	}

	/**
	 * map数据value排序
	 * 
	 * @param map
	 * @param string
	 * @return
	 */
	public static Map<String, Object> orderMapValue(Map<String, Object> map,
			final String order, int num) {
		Map<String, Object> mapRes = new LinkedHashMap<>();
		if (map != null && map.size() > 0) {
			Set<Entry<String, Object>> list = map.entrySet();
			List<Entry<String, Object>> entryList = new ArrayList<>();
			for (Entry<String, Object> entry : list) {
				entryList.add(entry);
			}

			Collections.sort(entryList,new Comparator<Entry<String, Object>>() {
				@Override
				public int compare(Entry<String, Object> o1,Entry<String, Object> o2) {
					int res = 0;
					Object v1 = o1.getValue();
					Object v2 = o2.getValue();
					if ("asc".equalsIgnoreCase(order)) {
						res = new Double(v1 + "").compareTo(new Double(v2+ ""));
					} else if ("desc".equalsIgnoreCase(order)) {
						res = new Double(v2 + "").compareTo(new Double(v1+ ""));
					}
					return res;
				}
			});
			for (Entry<String, Object> entry : entryList) {
				if(mapRes.size()==num){
					break;
				}
				mapRes.put(entry.getKey(), entry.getValue());
			}
		}
		return mapRes;
	}
}
